home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip1292.zip / REDIR.C < prev    next >
C/C++ Source or Header  |  1992-12-26  |  2KB  |  60 lines

  1. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2.  
  3.  
  4. Program: REDIR.C
  5. Author:  F. PIETTE (2:293/2201.135)
  6. Object:  Demonstration of the output redirection
  7. Creation: Augustus 2, 1991
  8. Updates:
  9.  
  10.  
  11.  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <io.h>
  15. #include <fcntl.h>
  16. #include <sys/types.h>
  17. #include <sys/stat.h>
  18.  
  19. void main(void)
  20. {
  21.     int old_fh;
  22.     int new_fh;
  23.  
  24.     fprintf(stdout, "This goes to the original standard output\n");
  25.  
  26.     /* Duplicate the stdout file handle to restore it later */
  27.     old_fh = dup(fileno(stdout));
  28.     if (old_fh == -1) {
  29.          fprintf(stderr, "dup error\n");
  30.          exit(1);
  31.     }
  32.  
  33.     /* Open the new file for output */
  34.     if ((new_fh = open("redir.txt", O_CREAT | O_TRUNC | O_WRONLY,
  35.                        S_IREAD | S_IWRITE)) == -1) {
  36.          fprintf(stderr, "Unable to open redir.txt\n");
  37.          exit(1);
  38.     }
  39.     /* Duplicate the new handle to stdout */
  40.     dup2(new_fh, fileno(stdout));
  41.     /* We don't need new_fh any more, so close it */
  42.     close(new_fh);
  43.  
  44.     /* stdout is now redirected, let's try it */
  45.     fprintf(stdout, "This goes to redir.txt file !\n");
  46.  
  47.     /* If you run a program using spawn(), the child program will have */
  48.     /* its output redirected to REDIR.TXT file ! */
  49.  
  50.     /* Now let's restore stdout to its original state */
  51.     fflush(stdout);  /* First flush the outut buffer */
  52.     /* Then duplicate the original file handle to stdout */
  53.     dup2(old_fh, fileno(stdout));
  54.  
  55.     /* Let's try if we canceled the redirection */
  56.     fprintf(stdout, "Back to original stdout\n");
  57.  
  58.     exit(0);
  59. }
  60.